package cn.i7baozh.starter.common.interceptor;

import cn.i7baozh.starter.common.exception.BussinessRuntimeException;
import cn.i7baozh.starter.common.response.WebResponseResult;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.entity.ContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 错误信息统一封装
 *
 * @author : baoqi.zhang
 * @date :   2022/5/21 1:02
 */
public class ErrorResultInterceptor implements HandlerInterceptor, WebMvcConfigurer {

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

        if (ex != null) {
            WebResponseResult error = WebResponseResult.error(ex.getMessage());
            if (ex instanceof BussinessRuntimeException) {
                error.setCode(((BussinessRuntimeException) ex).getCode());
            } else {
                error.setCode(HttpStatus.INTERNAL_SERVER_ERROR.value());
            }
            byte[] bytes = objectMapper.writeValueAsBytes(error);
//            response.setStatus(error.getCode());
            response.setContentType(ContentType.APPLICATION_JSON.toString());
            FileCopyUtils.copy(bytes, response.getOutputStream());
        }
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(this);
    }
}
